<style scoped>

</style>

<template>
  <a-select
    v-model:value="trainCode"
    show-search
    allowClear
    @change="onChange"
    placeholder="请选择车次"
    :filter-option="filterTrainCodeOption"
    :style="'width:' + localWidth"
  >
    <a-select-option v-for="item in trains" :key="item.code" :value="item.code" :label="item.code + item.start + item.end">
        {{item.code}} | {{ item.start }} ~ {{ item.end }}
    </a-select-option>
  </a-select>
</template>

<script>
import { defineComponent,ref,onMounted,watch} from 'vue';
import { notification } from 'ant-design-vue';
import axios from 'axios';
export default defineComponent({
  name: "trainSelect-view",
  // 定义父子组件参数传递的属性 --- modelValue是内置的变量
  props:["modelValue","width"],
  // 事件相关的对象数组，子组件向父组件传递事件
  emits:['update:modelValue','change'],
  setup(props,{emit}) {
    // 下拉框选择的对象
    const trains = ref([])
    const trainCode = ref()
    const localWidth = ref(props.width)
    // 设置自定义参数的默认值 --- 如果不设置就默认为100%
    if(window.Tool.isEmpty(props.width)){
      localWidth.value = "100%"
    }
    
    // 下拉框用于过滤的函数
    const filterTrainCodeOption = (input, option) => {
        return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    };

          // 火车信息下拉列表查询的方法
    const queryTrainCode= () => {
      console.log("queryTrainCode开始查询")
      axios.get("/business/train/query_all")
      .then( response => {
          console.log("queryTrainCode查询成功")
          console.log(response.data.data)
          trains.value = response.data.data
      })
      .catch( error => {
          // 关闭loading效果
          let errData = error.response.data
          console.log(errData)
          notification.error({ description: errData.data });
      })
    };

    onMounted(() => {
      queryTrainCode()
    });

    // 子组件向父组件传值
    const onChange = value => {
      // emit 触发一个事件
      emit('update:modelValue',value)
      let train = trains.value.filter(item => item.code === value )[0]
      if(window.Tool.isEmpty(train)){
        train = {}
      }
      emit('change',train)
    };

    // 监听props.modelValue 的变化
    watch(() => props.modelValue, () => {
      console.log("props.modelValue",props.modelValue)
      trainCode.value = props.modelValue
    },{immediate:true});

    return {
      trainCode,
      trains,
      localWidth,
      filterTrainCodeOption,
      queryTrainCode,
      onChange
    };
  },
});
</script>